package edu.buaa.agent.intecepter;

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import net.bytebuddy.matcher.ElementMatchers;

import java.io.IOException;
import java.lang.instrument.Instrumentation;

public class TimeInterceptorExample {

    public static void main(String[] args) throws IOException {
        // 1. 安装 Java Agent
        Instrumentation instrumentation = ByteBuddyAgent.install();
        
        // 2. 对 System 类中的方法进行拦截增强
        new ByteBuddy()
            .redefine(System.class)
            .visit(Advice.to(CurrentTimeInterceptor.class).on(ElementMatchers.named("currentTimeMillis")))
            .make()
            .load(System.class.getClassLoader(),
                    ClassReloadingStrategy.of(instrumentation).reset(System.class));

        // 测试拦截效果
        System.out.println(System.currentTimeMillis());
    }

    public static class CurrentTimeInterceptor {

        // 在方法执行前增强逻辑
        @Advice.OnMethodEnter
        public static void onEnter() {
            System.out.println("方法调用前：准备获取时间戳");
        }

        // 在方法执行后增强逻辑
        @Advice.OnMethodExit(onThrowable = Throwable.class)
        public static void onExit(@Advice.Return(readOnly = false) long returnValue) {
            System.out.println("方法调用后：原始时间戳为 " + returnValue);
            returnValue += 1000; // 示例：修改返回值，增加 1 秒
            System.out.println("方法调用后：修改后时间戳为 " + returnValue);
        }

    }
}
